package com.example.demo.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.demo.config.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

@Slf4j
@Service
@RestController
@RequestMapping("/upload")
public class FileService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;

    @PostMapping("/image")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            log.info("开始上传文件：{}", file.getOriginalFilename());
            if (file.isEmpty()) {
                return AjaxResult.fail("请选择要上传的图片");
            }
            String imageUrl = uploadFile(file);
            log.info("文件上传成功，URL：{}", imageUrl);
            return AjaxResult.success("上传成功", imageUrl);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return AjaxResult.fail("图片上传失败：" + e.getMessage());
        }
    }

    public String uploadFile(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        // 检查文件类型
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!".jpg".equals(extension) && !".jpeg".equals(extension) && 
            !".png".equals(extension) && !".gif".equals(extension)) {
            throw new IllegalArgumentException("只支持jpg、jpeg、png、gif格式的图片");
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + extension;
        String objectName = "images/" + fileName;

        log.info("开始上传文件到OSS，endpoint: {}, bucketName: {}, objectName: {}", 
                endpoint, bucketName, objectName);

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 上传文件
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            String fileUrl = urlPrefix + objectName;
            log.info("文件上传成功，访问URL: {}", fileUrl);
            return fileUrl;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new Exception("文件上传失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public void deleteFile(String fileUrl) {
        try {
            // 从URL中提取对象名称
            String objectName = fileUrl.substring(urlPrefix.length());
            
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            
            try {
                // 删除文件
                ossClient.deleteObject(bucketName, objectName);
                log.info("文件删除成功：{}", objectName);
            } finally {
                ossClient.shutdown();
            }
        } catch (Exception e) {
            log.error("删除文件失败：{}", fileUrl, e);
        }
    }
}